package com.mq.mqserver.datacenter;

import com.mq.common.exception.MqException;
import com.mq.mqserver.core.Binding;
import com.mq.mqserver.core.Exchange;
import com.mq.mqserver.core.MSGQueue;
import com.mq.mqserver.core.Message;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/*
* 使用这个类来管理所有硬盘上的数据
* 1.数据库：交换机、绑定、队列
* 2.数据文件：消息
* 上层逻辑如果需要操作硬盘，统一都通过这个类来使用（上层代码不关心当前数据是否存储在数据库还是文件中）
* */
public class DiskDataCenter {
    //实例化管理数据库数据
    private DataBaseManager dataBaseManager = new DataBaseManager();
    //实例化管理文件数据
    private MessageFileManager messageFileManager = new MessageFileManager();

    public void init(){
        //针对上述两个实例初始化
        dataBaseManager.init();
        //当前的messageFileManager.init是空的，只是先列在这里，方便后续扩展
        messageFileManager.init();
    }

    //封装交换机操作
    public void insertExchange(Exchange exchange){
        dataBaseManager.insertExchange(exchange);
    }

    public void deleteExchange(String exchangeName){
        dataBaseManager.deleteExchange(exchangeName);
    }

    public List<Exchange> selectAllExchange(){
        return dataBaseManager.selectAllExchanges();
    }

    //封装队列操作
    public void insertQueue(MSGQueue queue) throws IOException {
        dataBaseManager.insertQueue(queue);
        //创建队列的同时，不仅仅把队列对象写入数据库，还要创建出对应的目录和文件
        messageFileManager.createQueueFiles(queue.getName());
    }

    public void deleteQueue(String queueName) throws IOException {
        dataBaseManager.deleteQueue(queueName);
        //删除队列的同时，不仅仅把队列对象从数据库删除，还要删除出对应的目录和文件
        messageFileManager.destoryQueueFiles(queueName);
    }

    public List<MSGQueue> selectAllQueue(){
        return dataBaseManager.selectAllQueues();
    }

    //封装绑定操作
    public void insertBinding(Binding binding){
        dataBaseManager.insertBinding(binding);
    }

    public void deleteBinding(Binding binding){
        dataBaseManager.deleteBinding(binding);
    }

    public List<Binding> selectAllBinding(){
        return dataBaseManager.selectAllBindings();
    }

    //封装消息
    public void sendMessage(MSGQueue queue, Message message) throws IOException, MqException {
        messageFileManager.sendMessage(queue,message);
    }

    public void deleteMessage(MSGQueue queue,Message message) throws IOException, MqException, ClassNotFoundException {
        messageFileManager.deleteMessage(queue,message);

        if(messageFileManager.checkGC(queue.getName())){
            messageFileManager.GC(queue);
        }
    }

    public LinkedList<Message> loadAllMessageFromQueue(String queueName) throws IOException, MqException, ClassNotFoundException {
        return messageFileManager.loadAllMessageFromQueue(queueName);
    }


}
